#include "StdAfx.h"
#include "Thread.h"

CThread::CThread(void)
{
  m_hThread = NULL ;
  m_dwThreadID = 0;
  m_lpParam = NULL ;
  m_bExit = FALSE;
  m_lpfnThreadProc = NULL;
}

CThread::~CThread(void)
{
   WaitForSingleObject(m_hThread,500);
}

DWORD CThread::CreateThread(DWORD (*lpfnThreadCallBack)(LPVOID lpParam), LPVOID lpParam)
{ 
	DWORD dwThreadID = 0;
	
	::CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)lpfnThreadCallBack,lpParam,0,&dwThreadID);

	return dwThreadID;
}

void CThread::CreateThread(LPVOID lpParam)
{
    m_lpParam = lpParam ;
    
	m_hThread = ::CreateThread(NULL,0,ThreadProc,this,0,&m_dwThreadID);
}

DWORD CThread::ThreadProc(LPVOID lpParam) 
{
	CThread *pThis = (CThread*) lpParam;

	if (pThis != NULL)
	{
	   pThis->_Run( pThis->GetThreadParam());
	}
	return 0;
}


void  CThread::_Run(LPVOID lpParam)
{
     while(!m_bExit)
	 {
         if (m_lpfnThreadProc != NULL)
         {
            m_lpfnThreadProc(lpParam);
		 }
		 else
		 {
		     Run(lpParam);
		 }
	 }
}

void CThread::Run(LPVOID lpParam)
{
        

}


LPVOID CThread::GetThreadParam(void)
{
	return m_lpParam;
}

DWORD CThread::GetThreadID(void)
{
	return m_dwThreadID;
}

HANDLE CThread::GetThreadHandle(void)
{
	return m_hThread;
}

void CThread::ExitThread(void)
{
    m_bExit = TRUE ;
}

BOOL CThread::IsThreadRunning(void)
{
	if (m_hThread == NULL)
	{
	   return FALSE ;
	}
    
	DWORD dwExitCode = 0;
	
	::GetExitCodeThread(m_hThread,&dwExitCode);

	return ( dwExitCode == STILL_ACTIVE ) ;
}
